<template>
  <div class="product-box">
    <el-card v-if="!orderDetailVisible">
      <div class="header-wrapper">
        <div class="header-box">
          <el-carousel trigger="click" class="carousel-box">
            <el-carousel-item v-for="(item, index) in pictures" :key="index">
              <img class="img-box" :src="item" alt="" />
            </el-carousel-item>
          </el-carousel>

          <div class="intru-box">
            <div class="item-box">
              <div class="right">商品名称:</div>
              <div class="left">{{ productInfo.product_name }}</div>
            </div>
            <div class="item-box">
              <div class="right">商品描述:</div>
              <div class="left">{{ productInfo.product_description }}</div>
            </div>
            <div class="item-box">
              <div class="right">商品分类:</div>
              <div class="left">{{ productInfo.category_name }}</div>
            </div>
            <div class="item-box">
              <div class="right">商品库存:</div>
              <div class="left">{{ productInfo.stock }} 件</div>
            </div>
            <div class="item-box">
              <div class="right">商品价格:</div>
              <div class="left">
                <span style="color: #e6a23c">{{ productInfo.price }}</span
                >元
              </div>
            </div>
            <div class="item-box" style="display: flex; align-items: center">
              <div class="right" style="margin-right: 20px">收藏:</div>
              <el-button
                v-if="!isFavoriteFlag"
                type="primary"
                size="mini"
                title="点击收藏"
                @click="toCollect(productInfo.product_id)"
                >收藏</el-button
              >
              <el-button
                v-else
                title="点击取消收藏"
                type="info"
                size="mini"
                @click="toDeleteCollect(productInfo.product_id)"
                >已收藏</el-button
              >
            </div>
            <div class="item-box">
              <div class="right">购买:</div>
              <div class="left">
                <el-input-number
                  v-model="quantity"
                  :min="0"
                  :max="productInfo.stock"
                  label="购买件数"
                ></el-input-number>
              </div>
            </div>
            <div class="item-box">
              <div class="right">操作:</div>
              <div class="left">
                <div class="btn-box">
                  <div class="btn-item buy" @click="buyNow">立即购买</div>
                  <div class="btn-item cart" @click="addCart">加入购物车</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="comment-box">
          <el-card
            class="box-card"
            style="margin: 10px; height: 100%; overflow: auto"
          >
            <div
              v-loading="loading"
              slot="header"
              class="clearfix"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <span style="display: block; color: #409eff">评论列表</span>
            </div>
            <div v-if="commentList.length > 0" class="comment-wrapper">
              <div
                v-for="(item, index) in commentList"
                :key="index"
                class="comment-item"
              >
                <span class="comment-img">{{ item.username }}</span>
                <div class="comment-content">
                  <div class="comment-time">时间：{{ item.created_at }}</div>
                  <span class="comment-title"
                    >：{{ item.comment_content }}</span
                  >
                </div>
                <el-button
                  size="mini"
                  style="margin-left: 20px"
                  v-if="item.user_id == token"
                  type="danger"
                  @click="deleteComments(item.comment_id)"
                  >删除</el-button
                >
              </div>
            </div>
            <div class="empty-box-1" v-else>暂无评论</div>
          </el-card>
          <div class="comment-input-box">
            <el-input
              v-model="comment"
              @keyup.enter.native="addComment"
              placeholder="请输入评论"
            ></el-input>
            <el-button
              style="margin-left: 20px"
              type="primary"
              @click="addComment"
              >发送</el-button
            >
          </div>
        </div>
      </div>
    </el-card>

    <div class="order-detail" v-if="orderDetailVisible">
      <OrderDetail @goback="goback" :cartList="multipleSelection"></OrderDetail>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  isFavorite,
  addFavorites,
  deleteFavorites,
  getAllCommentsByProductId,
  addComments,
  deleteComments,
  addCart,
} from "@/api/user";
import OrderDetail from "@/views/home/components/CartIndex/components/OrderDetail.vue";

export default {
  name: "ProductDetail",
  components: { OrderDetail },
  props: {
    productInfo: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      orderDetailVisible: false,
      multipleSelection: [], //购买列表
      pictures: [],
      quantity: 0, //购买件数
      isFavoriteFlag: false,
      activeNames: "",
      comment: "",
      commentList: [],
      loading: false,
    };
  },
  watch: {
    productInfo: {
      handler(newValue) {
        console.log(newValue);
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters(["name", "role", "token"]),
  },
  created() {
    this.pictures = JSON.parse(this.productInfo.pictures);
  },
  async mounted() {
    this.getAllCommentsByProductId();
    await this.isFavorite();
  },
  methods: {
    async goback() {
      //清空购买数据
      this.multipleSelection = [];
      //返回商品详情
      this.orderDetailVisible = false;
      this.$emit("goback");
    },
    isLogin() {
      if (!this.token) return this.$message.warning("请先登录");
    },

    async buyNow() {
      if (!this.token) {
        this.$message.warning("请先登录,登录后再购买，1s后跳转到登录页！");
        return setTimeout(() => {
          this.$router.push("/login");
        }, 1000);
      }
      if (+this.quantity <= 0)
        return this.$message.warning("购买数量必须大于0");
      this.productInfo.stock = +this.productInfo.stock;
      this.quantity = +this.quantity;
      if (this.productInfo.stock < this.quantity) {
        return this.$message.warning("购买数量不能大于库存");
      }

      const data = {
        user_id: +this.token,
        product_id: this.productInfo.product_id,
        quantity: this.quantity,
        status: this.productInfo.status,
        category_name: this.productInfo.category_name,
        product_name: this.productInfo.product_name,
        price: this.productInfo.price,
        category_id: this.productInfo.category_id,
        pictures: this.productInfo.pictures,
        product_description: this.productInfo.product_description,
        stock: this.productInfo.stock,
        created_at: this.productInfo.created_at,
      };
      this.multipleSelection = [data];
      this.orderDetailVisible = true;
      this.$emit("toBuy");
    },
    async addCart() {
      if (!this.token) {
        this.$message.warning("请先登录,登录后再加购，1s后跳转到登录页！");
        return setTimeout(() => {
          this.$router.push("/login");
        }, 1000);
      }
      if (+this.quantity <= 0)
        return this.$message.warning("加购买数量必须大于0");
      this.productInfo.stock = +this.productInfo.stock;
      this.quantity = +this.quantity;
      const params = {
        user_id: +this.token,
        product_id: this.productInfo.product_id,
        quantity: this.quantity,
      };
      const res = await addCart(params);
      if (res.status == 0) {
        this.$message.success("添加成功");
      } else {
        this.$message.error("添加失败");
      }
    },
    async getAllCommentsByProductId() {
      this.loading = true;
      const { data: res } = await getAllCommentsByProductId(
        this.productInfo?.product_id
      );
      this.commentList = res || [];
      this.loading = false;
    },

    async addComment() {
      if (!this.token) return this.$message.warning("请先登录");
      const data = {
        user_id: +this.token,
        product_id: this.productInfo.product_id,
        comment_content: this.comment,
      };

      const res = await addComments(data);
      if (res.status == 0) {
        this.$message.success("评论成功");
        this.comment = "";
      } else {
        this.$message.error("评论失败");
      }
      this.getAllCommentsByProductId();
    },

    deleteComments(comment_id) {
      this.$confirm("此操作将永久删除该评论, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteComments(comment_id);
          if (res.status == 0) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: "删除成功!",
            });
          }
          this.getAllCommentsByProductId();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    async isFavorite() {
      if (!this.token) {
        this.isFavoriteFlag = false;
        return;
      }
      const params = {
        user_id: +this.token,
        product_id: this.productInfo.product_id,
      };
      const res = await isFavorite(params);
      console.log(params, res);
      if (res.status === 0) {
        this.isFavoriteFlag = res.isFavorite;
      }
    },
    async toCollect(product_id) {
      if (!this.token) {
        this.$message.warning("请先登录,登录后在收藏，1s后跳转到登录页！");
        return setTimeout(() => {
          this.$router.push("/login");
        }, 1000);
      }
      if (!product_id) return this.$message.warning("参数错误");
      const res = await addFavorites({
        user_id: +this.token,
        product_id: product_id,
      });
      if (res.status === 0) {
        this.$message({
          message: "收藏成功！",
          type: "success",
        });
      } else {
        this.$message({
          message: "收藏失败！",
          type: "warning",
        });
      }
      this.isFavoriteFlag = true;
    },
    //取消收藏
    async toDeleteCollect(product_id) {
      if (!this.token) {
        this.$message.warning("请先登录,登录后再取消收藏，1s后跳转到登录页！");
        return setTimeout(() => {
          this.$router.push("/login");
        }, 1000);
      }
      if (!product_id) return this.$message.warning("参数错误");
      const res = await deleteFavorites({
        user_id: +this.token,
        product_id: product_id,
      });
      if (res.status === 0) {
        this.$message({
          message: "取消收藏成功！",
          type: "success",
        });
      } else {
        this.$message({
          message: "取消收藏失败！",
          type: "warning",
        });
      }
      this.isFavoriteFlag = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.product-box {
  width: 100%;
  height: 100%;
  background-color: rgb(241, 241, 241);
  padding: 0 80px;

  .header-wrapper {
    // display: flex;
    // justify-content: space-between;
  }

  .header-box {
    flex: 1;
    margin: 20px auto;
    display: flex;

    .carousel-box {
      width: 300px;
    }
  }

  .comment-box {
    flex: 1;

    .el-card {
      ::v-deep .el-card__body {
        height: 254px;
        overflow-y: auto;
      }
    }
  }

  .intru-box {
    margin-left: 20px;
  }

  .img-box {
    // width: 180px;
    // height: 270px;
    width: 100%;
    height: 100%;
    display: block;
    margin-right: 30px;
  }

  .item-box {
    padding: 10px;
    display: flex;
    align-items: center;

    .right {
      font-size: 16px;
      color: #409eff;
      font-weight: 900;
      margin-right: 12px;
    }

    .left {
      font-size: 16px;
      font-weight: 900;
    }
  }
}

.comment-item {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-end;

  .comment-content {
    .comment-time {
      color: #999;
      margin-left: 15px;
      margin-bottom: 5px;
    }
  }
}

.comment-img {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  text-indent: 0;
  font-size: 20px;
  font-weight: 700;
  margin-right: 10px;
}

.comment-title {
  color: #409eff;
  font-weight: 700;
}

.empty-box {
  text-align: center;
}

.empty-box-1 {
  margin-top: 100px;
  text-align: center;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.btn-box {
  display: flex;
  border-radius: 12px;
  overflow: hidden;
  color: #fff;

  .btn-item {
    cursor: pointer;
    flex: 1 1 auto;
    font-family: PingFang SC;
    height: 48px;
    line-height: 48px;

    text-align: center;
    width: 240px;

    &.buy {
      background: linear-gradient(90deg, rgb(255, 119, 0), rgb(255, 73, 0));
    }

    &.cart {
      background: linear-gradient(90deg, rgb(255, 203, 0), rgb(255, 148, 2));
    }
  }
}

.comment-input-box {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 20px;
  margin-top: 20px;
}
</style>
